﻿using System;
using System.Web.UI.WebControls;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.Model;
using Kiiro.SiteDefinition.ControlTemplates;
using Kiiro.SiteDefinition.Core;
using Microsoft.SharePoint.Utilities;
using System.Collections.Generic;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint.WebControls;
using System.Linq;

namespace Kiiro.SiteDefinition.ProjectPages
{
    public partial class DisplayDiscussion : BasePage
    {
        private Discussion discussion = new Discussion ( );
        public Discussion Discussion
        {
            get { return discussion; }
            set { discussion = value; }
        }

        private List<User> discussionUsers;
        public List<User> DiscussionUsers
        {
            get { return discussionUsers; }
            set { discussionUsers = value; }
        }

        public AttachmentControl Attachments
        {
            get { return ( AttachmentControl ) attachmentControl; }
        }

        public AttachmentControl CommentAttachments
        {
            get { return ( AttachmentControl ) commentsEnabledAttachmentControl; }
        }

        public CustomFieldCollection CustomFields
        {
            get { return ( CustomFieldCollection ) v2CustomFieldCollection; }
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            CustomFields.ControlMode = Microsoft.SharePoint.WebControls.SPControlMode.Display;
            CustomFields.EntityType = typeof ( Discussion );
            CustomFields.Title = "Additional Information";

            litTitle.Text = "Display Discussion";
            if ( KiiroMaster.V2Header.Project != null && !string.IsNullOrEmpty ( KiiroMaster.V2Header.Project.Title ) )
            {
                litTitle.Text = KiiroMaster.V2Header.Project.Title + " - Display Discussion";
            }

            if ( ItemId > 0 )
            {
                Discussion = DiscussionModel.GetById ( ItemId, SiteCollectionId, ServerRelativeUrl );

                if ( Discussion != null )
                {
                    litTitle.Text = litTitle.Text + " - " + Discussion.Title;

                    // override page permissions and get object level permissions
                    PermissionsModel.GetGlobalPermissionBitsForCurrentUser ( Discussion, CurrentUser, SiteCollectionId, ServerRelativeUrl );

                    if ( Discussion.PermissionBitsDiscussions != null && Discussion.PermissionBitsDiscussions.Count > 0 )
                    {
                        lbDeleteDiscussion.Attributes.Add ( "onclick", "return confirm('Are you sure you wish to delete this discussion?')" );

                        imgCurrentUser.ImageUrl = CurrentUser.PictureUrl ?? "/_layouts/images/Kiiro/person-thumb.gif";

                        PopulateDiscussion ( Discussion );

                        create.Visible = Discussion.PermissionBitsDiscussions [ 0 ];
                        update.Visible = Discussion.PermissionBitsDiscussions [ 2 ];
                        delete.Visible = Discussion.PermissionBitsDiscussions [ 3 ];

                        btnAddComment.Visible = Discussion.PermissionBitsDiscussions [ 0 ];
                    }
                    else // security error
                        Redirect ( string.Empty );
                }
                else
                    Redirect ( string.Empty );
            }
            else
                Redirect ( string.Empty );
        }

        private void PopulateDiscussion ( Discussion discussion )
        {
            PopulateActionBar ( );

            List<int> userIds = new List<int> ( );
            foreach ( Comment comment in discussion.Comments )
            {
                userIds.Add ( comment.CreatedBy.Id );
                userIds.Add ( comment.ModifiedBy.Id );
            }

            if ( userIds != null && userIds.Count > 0 )
                DiscussionUsers = UserModel.GetUsersByIds ( userIds, SiteCollectionId, ServerRelativeUrl );

            lblDiscussionTitle.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( discussion.Title );

            if ( !string.IsNullOrEmpty ( discussion.HTMLText ) )
                litDiscussionText.Text = discussion.HTMLText;
            else
                litDiscussionText.Text = SPHelpers.CheckTextForLinks ( discussion.Text.Replace ( "\r\n", " <br/>" ) );

            if ( discussion.ModifiedDate != null && discussion.ModifiedDate != DateTime.MinValue )
                lblCreatedDate.Text = FormattingHelpers.DateTimeToDisplayDateStringNoLine ( discussion.ModifiedDate );
            else
                lblCreatedDate.Text = FormattingHelpers.DateTimeToDisplayDateStringNoLine ( discussion.CreatedDate );

            if ( discussion.CreatedBy != null && discussion.CreatedBy.Id > 0 )
            {
                User user = discussion.CreatedBy;
                if ( string.IsNullOrEmpty ( user.FullName ) )
                {
                    user = UserModel.GetUserById ( discussion.CreatedBy.Id, SiteCollectionId, ServerRelativeUrl );
                }
                hlCreatedBy.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( user.FullName );
                if ( !user.IsDeleted )
                    hlCreatedBy.NavigateUrl = String.Format ( "{0}{1}?id={2}", ServerRelativeUrl, Constants.PortalFileUrls.UserDisplay, user.SPUserId );

                imgCreatedBy.ImageUrl = user.PictureUrl ?? "/_layouts/images/Kiiro/person-thumb.gif";
            }

            // set control mode to display before calling SetAttachments (default is edit mode)
            if ( discussion.AttachmentList != null && discussion.AttachmentList.Count > 0 )
            {
                Attachments.ControlMode = PageMode.Display;
                Attachments.SetAttachments ( discussion.AttachmentList );
            }
            else
            {
                pnlAttachmentSettings.Visible = false;
            }

            discussion.Comments.Sort ( CompareByCreatedDateReverseChronological );
            rptComments.DataSource = discussion.Comments;
            rptComments.DataBind ( );

            commentContent.Attributes.Add ( "class", "panel-content" );
        }

        public static int CompareByCreatedDateReverseChronological ( BaseEntity x, BaseEntity y )
        {
            // left in addtional error handling for when method is extracted out and multiple BaseEntitys utilize
            if ( y == null )
            {
                if ( x == null )
                    return 0;
                else
                    return -1;
            }
            else
            {
                if ( x == null )
                    return 1;
                else
                {
                    // y needs to go first because it is a descending sort
                    return y.CreatedDate.CompareTo ( x.CreatedDate );
                }
            }
        }

        private void PopulateActionBar ( )
        {
            if ( Request.UrlReferrer != null )
            {
                if ( Request.UrlReferrer.OriginalString.ToLower ( ).Contains ( Constants.ProjectFileUrls.DiscussionsAll.ToLower ( ) ) )
                {
                    lnkBackToDiscussions.NavigateUrl = ServerRelativeUrl + Constants.ProjectFileUrls.DiscussionsAll;
                    lnkBackToDiscussions.Text = "Back to All Discussions";
                }
                else if ( Request.UrlReferrer.OriginalString.ToLower ( ).Contains ( Constants.ProjectFileUrls.ProjectSummary.ToLower ( ) ) )
                {
                    lnkBackToDiscussions.NavigateUrl = Request.UrlReferrer.OriginalString;
                    lnkBackToDiscussions.Text = "Back to Summary Page";
                }
                else if ( Request.UrlReferrer.OriginalString.ToLower ( ).Contains ( Constants.PortalFileUrls.PortalActivity.ToLower ( ) ) )
                {
                    lnkBackToDiscussions.NavigateUrl = Request.UrlReferrer.OriginalString;
                    lnkBackToDiscussions.Text = "Back to Recent Activity Page";
                }
                else if ( Request.UrlReferrer.OriginalString.ToLower ( ).Contains ( Constants.PortalFileUrls.SearchResults.ToLower ( ) ) )
                {
                    lnkBackToDiscussions.NavigateUrl = Request.UrlReferrer.OriginalString;
                    lnkBackToDiscussions.Text = "Back to Search Page";
                }
                else
                {
                    lnkBackToDiscussions.NavigateUrl = ServerRelativeUrl + Constants.ProjectFileUrls.DiscussionsAll;
                    lnkBackToDiscussions.Text = "Back to All Discussions";
                }
            }
            else
            {
                lnkBackToDiscussions.NavigateUrl = ServerRelativeUrl + Constants.ProjectFileUrls.DiscussionsAll;
                lnkBackToDiscussions.Text = "Back to All Discussions";
            }
        }

        protected void rptComments_ItemDataBound ( object source, RepeaterItemEventArgs e )
        {
            Comment comment = ( Comment ) e.Item.DataItem;
            RepeaterItem repeater = ( RepeaterItem ) e.Item;

            if ( comment.CreatedBy != null )
            {
                User author = DiscussionUsers.Find ( x => x.Id == comment.CreatedBy.Id );

                HyperLink hlCommentCreatedBy = ( HyperLink ) repeater.FindControl ( "hlCommentCreatedBy" );
                if ( hlCommentCreatedBy != null && author != null )
                {
                    hlCommentCreatedBy.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( author.FullName );
                    if ( !author.IsDeleted )
                        hlCommentCreatedBy.NavigateUrl = String.Format ( "{0}{1}?id={2}", ServerRelativeUrl, Constants.PortalFileUrls.UserDisplay, author.SPUserId );
                }

                Image imgComment = ( Image ) repeater.FindControl ( "imgComment" );
                if ( imgComment != null && author != null )
                {
                    imgComment.ImageUrl = author.PictureUrl ?? "/_layouts/images/Kiiro/person-thumb.gif";
                }
            }

            Literal commentAnchor = ( Literal ) repeater.FindControl ( "commentAnchor" );
            if ( commentAnchor != null )
            {
                commentAnchor.Text = "<a name='post" + comment.Id + "'></a>";
            }

            Label lblCommentCreatedDate = ( Label ) repeater.FindControl ( "lblCommentCreatedDate" );
            if ( lblCommentCreatedDate != null )
            {
                if ( comment.ModifiedDate != null && comment.ModifiedDate != DateTime.MinValue )
                    lblCommentCreatedDate.Text = FormattingHelpers.DateTimeToDisplayDateStringNoLine ( comment.ModifiedDate );
                else if ( comment.ModifiedDate != null && comment.ModifiedDate != DateTime.MinValue )
                    lblCommentCreatedDate.Text = FormattingHelpers.DateTimeToDisplayDateStringNoLine ( comment.CreatedDate );
            }

            Label lblCommentText = ( Label ) repeater.FindControl ( "lblCommentText" );
            if ( lblCommentText != null && comment.Text != null )
            {
                string textValue = SPHelpers.FormatCommentText(comment.Text);
                lblCommentText.Text = SPHelpers.CheckTextForLinks(textValue);
            }

            if ( CurrentUser.Groups.Contains ( KiiroGroup.PortalOwner ) || CurrentUser.Groups.Contains ( KiiroGroup.ProjectOwner ) ||
                ( CurrentUser.Groups.Contains ( KiiroGroup.ProjectMember ) && comment.AuthorId == CurrentUser.Id ) )
            {
                LinkButton btnEditComment = ( LinkButton ) repeater.FindControl ( "btnEditComment" );
                if ( btnEditComment != null )
                {
                    btnEditComment.Text = "Edit";
                    btnEditComment.Attributes.Add ( "class", "update" );
                    btnEditComment.CommandArgument = comment.Id.ToString ( );
                    btnEditComment.Click += new EventHandler ( btnEditComment_Click );
                }

                LinkButton btnDeleteComment = ( LinkButton ) repeater.FindControl ( "btnDeleteComment" );
                if ( btnDeleteComment != null )
                {
                    btnDeleteComment.Text = "Delete";
                    btnDeleteComment.Attributes.Add ( "onclick", "return confirm('Are you sure you wish to delete this comment?')" );
                    btnDeleteComment.Attributes.Add ( "class", "update" );
                    btnDeleteComment.CommandArgument = comment.Id.ToString ( );
                    btnDeleteComment.Click += new EventHandler ( btnDeleteComment_Click );
                }
            }

            AttachmentControl commentAttachmentsControl = ( AttachmentControl ) repeater.FindControl ( "commentsAttachmentControl" );
            if ( commentAttachmentsControl != null )
            {
                if ( comment.AttachmentList != null && comment.AttachmentList.Count > 0 )
                {
                    commentAttachmentsControl.ControlMode = PageMode.Display;
                    commentAttachmentsControl.SetAttachments ( comment.AttachmentList );
                }
                else
                {
                    commentAttachmentsControl.Visible = false;
                }
            }
        }

        protected void btnDeleteComment_Click ( object sender, EventArgs e )
        {
            // security check done on row binding
            LinkButton linkButton = ( LinkButton ) sender;
            int commentId = int.Parse ( linkButton.CommandArgument );

            // need to get the CreatedBy property for security
            Comment comment = CommentModel.GetById ( commentId, SiteCollectionId, ServerRelativeUrl );

            if ( comment != null )
            {
                comment.EditType = EditType.Deleted;
                comment.ModifiedBy = CurrentUser;
                CommentModel.Save ( comment, SiteCollectionId, ServerRelativeUrl );

                Response.Redirect ( String.Format ( "{0}{1}?id={2}", ServerRelativeUrl, Constants.ProjectFileUrls.DiscussionDisplay, ItemId ) );
            }
        }

        protected void btnEditComment_Click ( object sender, EventArgs e )
        {
            // security check done on row binding
            LinkButton linkButton = ( LinkButton ) sender;
            Response.Redirect ( String.Format ( "{0}{1}?id={2}", ServerRelativeUrl, Constants.ProjectFileUrls.CommentEdit, linkButton.CommandArgument ) );
        }

        protected void lbNewDiscussion_Click ( object sender, EventArgs e )
        {
            if ( Discussion.PermissionBitsDiscussions [ 0 ] )
                Response.Redirect ( String.Format ( "{0}{1}", ServerRelativeUrl, Constants.ProjectFileUrls.DiscussionNew ) );
        }

        protected void lbEditDiscussion_Click ( object sender, EventArgs e )
        {
            if ( Discussion.PermissionBitsDiscussions [ 2 ] )
                Response.Redirect ( String.Format ( "{0}{1}?id={2}", ServerRelativeUrl, Constants.ProjectFileUrls.DiscussionEdit, ItemId ) );
        }

        protected void lbDeleteDiscussion_Click ( object sender, EventArgs e )
        {
            if ( Discussion.PermissionBitsDiscussions [ 3 ] )
            {
                Discussion.EditType = EditType.Deleted;
                Discussion.ModifiedBy = CurrentUser;
                DiscussionModel.Save ( Discussion, SiteCollectionId, ServerRelativeUrl );
                Redirect ( string.Empty );
            }
        }

        protected void btnAddComment_Click ( object sender, EventArgs e )
        {
            if ( PermissionBitsDiscussions [ 0 ] && ItemId > 0 )
            {
                Comment comment = new Comment ( );
                comment.EditType = EditType.Created;
                comment.ModifiedBy = CurrentUser;
                comment.ModifiedDate = DateTime.Now;
                comment.CreatedBy = CurrentUser;
                comment.CreatedDate = DateTime.Now;
                comment.ServerRelativeUrl = ServerRelativeUrl.Length > 1 ? ServerRelativeUrl : "/";
                comment.SiteCollectionId = SiteCollectionId;
                comment.AttachmentList = CommentAttachments.GetAttachments ( );

                comment.DiscussionId = Discussion.Id;
                comment.Text = txtComment.Text;

                comment = CommentModel.Save ( comment, SiteCollectionId, ServerRelativeUrl );

                Redirect ( comment );
            }
        }

        private void Redirect ( string redirectUrl )
        {
            string url = default ( string );

            url = ServerRelativeUrl + Constants.ProjectFileUrls.DiscussionsAll;

            if ( !string.IsNullOrEmpty ( redirectUrl ) )
            {
                url = redirectUrl;
            }

            if ( Request.Params [ "Source" ] != null )
            {
                url = Request.Params [ "Source" ];
            }

            Response.Redirect ( url );
        }

        private void Redirect ( Comment comment )
        {
            if ( comment.IsValid ( ) )
            {
                Response.Redirect ( String.Format ( "{0}{1}?id={2}", ServerRelativeUrl, Constants.ProjectFileUrls.DiscussionDisplay, ItemId ) );
            }
            else
            {
                lblCommentMessage.Text = FormattingHelpers.GetErrorMessageText ( comment.TextMessage );
            }
        }
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.ProjectPages/Discussions/DisplayDiscussions.aspx.cs $
 * 
 * 30    1/15/10 12:36p Camerons
 * 
 * 29    1/15/10 9:49a Camerons
 * 
 * 28    1/15/10 9:14a Camerons
 * 
 * 27    1/14/10 12:46p Camerons
 * 
 * 26    1/13/10 6:15p Camerons
 * 
 * 25    14/12/09 2:04p Adamw
 * changed to sort discussion comments by created date
 * 
 * 24    12/09/09 1:54p Shafia
 * 
 * 23    26/11/09 2:31p Shafia
 * 
 * 22    26/11/09 2:23p Shafia
 * 
 * 21    24/11/09 10:55a Shafia
 * Discussion now stores the HTML format of the discussion text and uses
 * the WMD editor
 * 
 * 20    31/10/09 12:15p Camerons
 * 
 * 19    29/10/09 3:17p Camerons
 * 
 * 18    28/10/09 11:01a Camerons
 * 
 * 17    26/10/09 5:36p Shafia
 * 
 * 16    10/26/09 9:36a Adamw
 * 
 * 15    10/23/09 5:35p Adamw
 * Case 348
 * 
 * 14    10/23/09 2:13p Adamw
 * Case 332
 * 
 * 13    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 12    30/09/09 9:48a Shafia
 * 
 * 11    23/09/09 4:34p Shafia
 * implemented the new WelcomeMessagePanel user control on Projects,
 * Users, CustomLists, Work, Documents, and Discussions pages.
 * Links are being displayed based on PermissionsBits[Entity]
 * 
 * 10    22/09/09 9:59a Shafia
 * Implemented New Pager
 * 
 * 9     18/09/09 1:24p Camerons
 * 
 * 8     17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/